<?php
declare(strict_types=1);
namespace app\admin\widget;
use aphp\core\Widget;
use extend\layui\Form;
class MakeView extends Widget
{
    protected string $tag = 'model';
    protected int $expire = 0;
    public function set($id = '', array $options = []): array
    {
        $model = db('model')->where('table_name', $id)->find();
        if (!$model) {
            return [];
        }
        $tpl = $options['tpl'] ?? 'index';
        $model_field = widget('admin.model_field')->get($model['id']); //模型字段
        $form = Form::init($model['id']);
        $html = [];
        foreach ($model_field as $k => $vo) {
            if ($tpl == 'index' && $vo['show_list'] == 1) {
                $k ++;
                if ($vo['field_name'] == 'sort') {
                    $k = 0;
                }
                $html[$k] = $form->makeTableCols($vo);
            } elseif ($tpl == 'add' && $vo['show_add'] == 1) {
                $html[] = $form->make($vo);
            } elseif ($tpl == 'edit' && $vo['show_edit'] == 1) {
                $html[] = $form->make($vo, 1);
            }
        }
        if ($tpl == 'add' || $tpl == 'edit') {
            return ['form_items' => implode("\n", $html)];
        }
        ksort($html);
        $html = array_map(fn($v)=>"\t\t\t\t".$v, $html);
        $replace = [];
        $replace['quick_search'] = $model['quick_search'];
        $replace['form_search'] = $model['form_search'];
        $replace['url_search'] = $model['url_search'];
        $replace['form_visible'] = $model['form_visible'];
        $replace['form_toggle'] = $model['form_toggle'];
        $replace['is_page'] = $model['list_limit'] > 0 ? '1' : '0';
        $replace['table_cols'] = implode("\n", $html);
        return $replace;
    }
}